import DragComponent from "../game/DragComponent";
import BlockManager, { IBlock, IDragData, BlockType, blockTypeVals } from "../game/BlockManager";
import Utils from "../common/Util";
import SceneCom from "./SceneCom";
import GameManager from "../common/GameManager";
import SceneManager from "./SceneManager";
import AudioManager from "../common/AudioManager";
import PropManager from "../game/PropManager";
import { PropPromptPanel, PROP_TYPE } from "../game/PropPromptPanel";
import EventConst from "../game/EventConst";
import UserData from "../common/UserData";
import Facebook from "../Facebook/Facebook";
import { GameConfig } from "../common/GameConfig";
import Logger from "../Logger/Logger";
import MsgSystem from "../MsgSystem/MsgSystem";
import MsgDefine from "../MsgSystem/MsgDefine";
import EventUtils from "../gmbox/EventUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameScene extends SceneCom {

    @property(cc.Node)
    gridContainer: cc.Node = null;

    @property(cc.Node)
    dragContainer: cc.Node = null;

    @property([cc.SpriteFrame])
    gridArr: cc.SpriteFrame[] = [];

    @property(cc.SpriteFrame)
    hint: cc.SpriteFrame = null;

    @property(cc.Node)
    headImg: cc.Node = null;

    @property(cc.Label)
    nick: cc.Label = null;

    @property(cc.Label)
    id: cc.Label = null;

    private _blockManager: BlockManager;
    private _curMatchGrid: IBlock[] = [];
    private _orginPos: cc.Vec2;
    private _manager: GameManager;
    private _propOriginPos: cc.Vec2;
    private _propPromptPanel: cc.Node;
    private _firstPut: boolean = true;

    onLoad() {
        GameManager.getInstance().gameData.ReadGameArchive();
        //设置声音
        GameConfig.SoundSwitch = GameManager.getInstance().gameData.getSoundSwitch();
        //背景音乐
        GameManager.getInstance().audioManager.playBackgroundMusic();

        UserData.init();

        let blockManager: BlockManager = BlockManager.getInstance();
        blockManager.gridSpriteFrameArr = this.gridArr;
        blockManager.hintSpriteFrame = this.hint;

        //打点分析
        // GameanalyticsMgr.init();
    }
    onShow() {
        super.onShow();
        this._manager = GameManager.getInstance();
        this._blockManager = BlockManager.getInstance();
        this._orginPos = this.dragContainer.position;

        if (typeof FBInstant != 'undefined') {
            Utils.LoadHeadImg(this.headImg, FBInstant.player.getPhoto());
            this.nick.string = FBInstant.player.getName();
        }

        if (typeof gmbox != 'undefined') {
            setTimeout(() => {
                gmbox.loadingComplete();
            }, 200);
        }

        EventUtils.logEvent("on_main_scene")

        let child: cc.Node;
        for (let i = 0; i < this.gridContainer.childrenCount; i++) {
            child = this.gridContainer.children[i];
            let index: number = child.getComponent("Block").index;
            this._blockManager.blockArr[index].pos = this.gridContainer.convertToWorldSpaceAR(child.position);
            this._blockManager.blockArr[index].node = child;

        }

        // this.buildNextDragGrid();

        this.node.on("touch_end", this.touchEndHandler, this);
        this.node.on("touch_move", this.touchMoveHandler, this);
        this._manager.eventCenter.RegisterEvent(this.uuid, "restart", this.restartHandler.bind(this));
        this._manager.eventCenter.RegisterEvent(this.uuid, "go_lobby", this.goLobbyHandler.bind(this));
        this._manager.eventCenter.RegisterEvent(this.uuid, "gameover", this.gameoverHandler.bind(this));
        this._manager.eventCenter.RegisterEvent(this.uuid, "refresh_dragdata", this.refreshHandler.bind(this));
        this._manager.eventCenter.RegisterEvent(this.uuid, "removeBlock", this.removeBlockHandler.bind(this));
        this._manager.eventCenter.RegisterEvent(this.uuid, EventConst.PROP_CANCLE, this.removePropPromptPanel.bind(this));

        
        //读取存档
        this.readArchive();
        // this.showReadArchiveDialog();
    }

    private showReadArchiveDialog() {
        this.readArchive();
        if (BlockManager.getInstance().checkGameOver()) {
            Logger.log("there is no gameover!!")
            this.openReadArchive();
        }
    }

    private _rulePage: cc.Node;
    private openReadArchive() {
        Utils.GetPrefab("prefab/GameRestart.prefab", (prefab) => {
            if (prefab && (!this._rulePage || !this._rulePage.parent)) {
                this._rulePage = cc.instantiate(prefab);
                this.node.addChild(this._rulePage);
            }
        }, this)
    }

    onHide() {
        super.onHide();
        this.node.off("touch_end", this.touchEndHandler, this);
        this.node.off("touch_move", this.touchMoveHandler, this);
        this.node.off(cc.Node.EventType.TOUCH_START, this.touchStartHandler, this);
        this._manager.eventCenter.RemoveEvent(this.uuid);
    }
    start() {
        MsgSystem.GetInstance().AddListener(MsgDefine.restartGame, () => {
            this.restartHandler();
        }, this);

        MsgSystem.GetInstance().AddListener(MsgDefine.revivialGame, () => {
            this._blockManager.revivalGame();
            this.buildNextDragGrid();
        }, this);
    }

    update(dt) {
    }

    /**
     * 道具相关
     * @param event 
     */
    private touchStartHandler(event): void {
        this.node.off(cc.Node.EventType.TOUCH_START, this.touchStartHandler, this);
        if (this._addPointPropState == 1) {
            var pos = event.getLocation();
            let block = this.detectLen1(pos);
            if (block.len < 60) {
                if (block.block.type >= BlockType.HT_2) {
                    let node: cc.Node = new cc.Node();
                    node.parent = block.block.node;
                    block.block.node.zIndex = 999;
                    Utils.AddAutoRemoveEffect(node, "prefab/finger_knock_motion", "Knock", () => {
                        GameManager.getInstance().audioManager.playEffect("finger");
                        //播放特效
                        Utils.GetPrefab("prefab/Light", (prefab: cc.Prefab) => {
                            block.block.type += 1;
                            this._manager.gameData.AddHexagon(block.block.type, block.block.index);
                            PropManager.getInstance().changeProp(1, -1);
                            this.merger([block.block])

                            let node: cc.Node = cc.instantiate(prefab);
                            node.getComponent(cc.Sprite).spriteFrame = BlockManager.getInstance().gridSpriteFrameArr[block.block.type];
                            node.parent = block.block.node.parent;
                            node.position = block.block.node.position;
                            node.zIndex = 1000;
                            setTimeout(() => {
                                node.destroy();
                            }, 200);
                        })
                    }, this);
                }
            }
            this.removePropPromptPanel();
        } else if (this._removeBlockPropState == 1) {
            var pos = event.getLocation();
            let block = this.detectLen1(pos);
            if (block.len < 60) {
                if (block.block.type != BlockType.none) {
                    let node: cc.Node = new cc.Node();
                    node.parent = block.block.node;
                    block.block.node.zIndex = 999;
                    Utils.AddAutoRemoveEffect(node, "prefab/hammer_knock_motion", "Knock", () => {
                        let audioManager: AudioManager = GameManager.getInstance().audioManager;
                        audioManager.playEffect("chuizi");

                        let addScore: number = blockTypeVals[block.block.type] * 2;
                        this._manager.gameData.AddCurScore(addScore);
                        this._manager.eventCenter.DispatchEvent("block_score_update", { pos: block.block.pos, score: addScore });

                        block.block.type = BlockType.none;
                        this._manager.gameData.AddHexagon(block.block.type, block.block.index);
                        PropManager.getInstance().changeProp(2, -1);
                    }, this);

                }
            }
            this.removePropPromptPanel();
        }
    }

    private touchMoveHandler(evt: any) {
        if (this._rotating) {
            (this.getComponent("DragComponent") as DragComponent).resetPos();
            return;
        }

        let pos: cc.Vec2 = evt.pos;
        let type: number = evt.type;
        this.dragContainer.position = this.dragContainer.position.lerp(pos, 1);
        for (let i = 0; i < this.gridContainer.childrenCount; i++) {
            let child = this.gridContainer.children[i];
            child.opacity = 255;
        }
        if (this.matchMap()) {
            this._curMatchGrid.forEach(element => {
                element.node.opacity = 100;
            });
        }
    }

    private _rotating: boolean = false;
    private _originRotation: number = 0;
    private async touchEndHandler(evt: any) {
        if (this._rotating) {
            return;
        }
        let isShortClick: boolean = evt.isShortClick;
        let self = this;
        let duration: number = 0.2;
        if (isShortClick) {//单击
            (this.getComponent("DragComponent") as DragComponent).resetPos();
            if (this._blockManager.dragData.posType == 0) { //当个不旋转
                return;
            }
            this._rotating = true;
            let audioManager: AudioManager = GameManager.getInstance().audioManager;
            audioManager.PlaySoundEffect(audioManager.SoundType.ST_RotateHexagon);
            for (let i = 0; i < this.dragContainer.childrenCount; i++) {
                let child: cc.Node = this.dragContainer.children[i];
                if (this.dragContainer.childrenCount > 1) {
                    child.runAction(cc.rotateBy(duration, 180));
                }
            }
            this.dragContainer.runAction(cc.sequence(cc.rotateBy(duration, 180), cc.delayTime(0.1), cc.callFunc(() => {
                this._rotating = false;
            })));
            return;
        }

        if(this._firstPut) {
            this._firstPut = false;
            EventUtils.logEvent("first_put")
        }

        let audioManager: AudioManager = this._manager.audioManager;
        if (this.matchMap()) {
            audioManager.PlaySoundEffect(audioManager.SoundType.ST_PlaceSuccess);
            for (let i = 0; i < this.dragContainer.childrenCount; i++) {
                let child: cc.Node = this.dragContainer.children[i];
                // let duration: number = this._curMatchGrid[i].pos.sub(this.node.convertToWorldSpaceAR(this.dragContainer.position)).mag() / 500;
                // let node: cc.Node = cc.instantiate(child);
                // this.worldNode.addChild(node);
                // node.setPosition(this.worldNode.convertToNodeSpaceAR(this.dragContainer.convertToWorldSpaceAR(child.position)));
                child.active = false;
                // await new Promise((resolve) => {
                //     node.runAction(cc.sequence(cc.moveTo(duration, this.worldNode.convertToNodeSpaceAR(this._curMatchGrid[i].pos)), cc.callFunc(() => {
                // node.destroy();
                self._curMatchGrid[i].type = self._blockManager.dragData.blockArr[i];
                this._manager.gameData.AddHexagon(self._curMatchGrid[i].type, self._curMatchGrid[i].index);
                //         resolve();
                //     }, this)))
                // });
            }
            // await new Promise((resovle) => {
            //     setTimeout(() => {
            //         resovle();
            //     }, 10);
            // })
            await this.merger(this._curMatchGrid);
            self.buildNextDragGrid(true, true);
        } else {
            audioManager.PlaySoundEffect(audioManager.SoundType.ST_PlaceFail);
            this._curMatchGrid.forEach(element => {
                element.node.opacity = 255;
            });
            (this.getComponent("DragComponent") as DragComponent).resetPos();
        }
    }

    /**
     * 执行合并
     * @param curMatchGrid 
     */
    private async merger(curMatchGrid: IBlock[]) {
        let self = this;
        let totalMergeCount: number = 0;
        this._mergeCount = 0;
        //小的先消
        curMatchGrid.sort((a, b) => {
            return a.type - b.type;
        })
        let mergeCount: number = this._mergeCount = 0;
        while (this._mergeCount == mergeCount) {
            await self.mergeGrid([curMatchGrid[0]], this._mergeCount > 0);
            mergeCount++;
        }
        totalMergeCount += this._mergeCount;

        let isMerged: boolean = !!(this._mergeCount > 0);
        this._mergeCount = mergeCount = 0;
        if (isMerged) {
            this._mergeCount = mergeCount = 1;
        }
        if (curMatchGrid[1]) {
            while (this._mergeCount == mergeCount) {
                await self.mergeGrid([curMatchGrid[1]], this._mergeCount > 0);
                mergeCount++;
            }
        }
        if (isMerged) {
            totalMergeCount += this._mergeCount - 1;
        } else {
            totalMergeCount += this._mergeCount;
        }

        isMerged = !!(this._mergeCount > 0);
        if (isMerged) {
            this._mergeCount = mergeCount = 0;
            while (this._mergeCount == mergeCount) {
                await self.mergeGrid([curMatchGrid[0]], true);
                mergeCount++;
            }
            totalMergeCount += this._mergeCount;
        }
        this.playEncourage(totalMergeCount);
    }

    /**
     * 判断空位置的合法性
     * @param pos 
     */
    private matchMap(): boolean {
        if (this.detectMatch()) {
            return true;
        }
        return false;
    }

    private detectMatch(): boolean {
        this._curMatchGrid = [];
        let child: cc.Node;
        let arr: IBlock[] = [];
        for (let i = 0; i < this.dragContainer.childrenCount; i++) {
            child = this.dragContainer.children[i];
            let block = this.detectLen(this.dragContainer.convertToWorldSpaceAR(child.position));
            if (block.len > 50) {
                return false;
            }
            if (!arr.length) {
                arr.push(block.block);
            } else if (arr.length && block.block.pos.sub(arr[0].pos).mag() > 110) {
                return false;
            }

            this._curMatchGrid.push(block.block);
        }

        return true;
    }

    /**
     * 检查空的
     * @param pos 
     */
    private detectLen(pos: cc.Vec2): { block: IBlock, len: number } {
        var arr: IBlock[] = [];
        let blockArr = this._blockManager.blockArr;
        for (let i = 0; i < blockArr.length; i++) {
            let block: IBlock = blockArr[i];
            if (block.type == BlockType.none) {
                arr.push(block);
            }
        }
        arr.sort((a, b) => {
            return a.pos.sub(pos).mag() - b.pos.sub(pos).mag();
        })

        return {
            block: arr[0],
            len: arr[0].pos.sub(pos).mag()
        }
    }

    /**
     * 检查非空的
     * @param pos 
     */
    private detectLen1(pos: cc.Vec2): { block: IBlock, len: number } {
        var arr: IBlock[] = [];
        let blockArr = this._blockManager.blockArr;
        for (let i = 0; i < blockArr.length; i++) {
            let block: IBlock = blockArr[i];
            if (block.type != BlockType.none) {
                arr.push(block);
            }
        }
        arr.sort((a, b) => {
            return a.pos.sub(pos).mag() - b.pos.sub(pos).mag();
        })

        return {
            block: arr[0],
            len: arr[0].pos.sub(pos).mag()
        }
    }

    private gameOver() {
        if(this._blockManager.hasRevivalTimes()) {//还有复活次数
            Utils.GetPrefab("prefab/RevivalGame.prefab", (prefab) => {
                if (!prefab) return;
                var gameoverLayerNode = cc.instantiate(prefab);
                if (gameoverLayerNode) {
                    this.node.addChild(gameoverLayerNode);
                }
            }, this);
        } else {
            Utils.GetPrefab("prefab/GameOverLayer.prefab", (prefab) => {
                if (!prefab) return;
                var gameoverLayerNode = cc.instantiate(prefab);
                if (gameoverLayerNode) {
                    this.node.addChild(gameoverLayerNode);
                }
            }, this);
        }
    }

    /** 
     * 生成下一个
    */
    private async buildNextDragGrid(isBuild: boolean = true, checkGameOver: boolean = false) {
        //游戏结束
        if (checkGameOver && BlockManager.getInstance().checkGameOver()) {
            this.gameOver();
            return;
        }
        this.dragContainer.stopAllActions();
        this.dragContainer.scale = 1;
        this.dragContainer.rotation = 0;
        this.dragContainer.zIndex = this.node.childrenCount - 1;
        this.dragContainer.setPosition(this._orginPos);
        this.dragContainer.destroyAllChildren();
        if (isBuild) {
            this._blockManager.buildDragData();
        }
        let dragData: IDragData = this._blockManager.dragData;

        let node1: cc.Node = BlockManager.getInstance().getGridNodeByType(dragData.blockArr[0]);
        node1.parent = this.dragContainer;
        if (dragData.blockArr[0] == dragData.blockArr[1]) {
            let hintNode = BlockManager.getInstance().getHintNode();
            node1.addChild(hintNode);
            hintNode.runAction(cc.sequence(cc.scaleTo(1, 0.9), cc.scaleTo(1, 1.1)).repeatForever());
        }
        let node2: cc.Node;
        if (dragData.posType != 0) {
            node2 = BlockManager.getInstance().getGridNodeByType(dragData.blockArr[1]);
            node2.parent = this.dragContainer;
        }

        if (node1) {
            node1.scale = 0.7;
        }
        if (node2) {
            node2.scale = 0.7;
        }

        switch (dragData.posType) {
            case 0: {
                node1.setPosition(0, 0);
                break;
            }
            case 1: {
                node1.setPosition(-45, 0);
                node2.setPosition(45, 0);
                break;
            }
            case 2: {
                node1.setPosition(24, 40);
                node2.setPosition(-24, -40);
                break;
            }
            case 3: {
                node1.setPosition(-24, 40);
                node2.setPosition(24, -40);
                break;
            }
        }
    }

    /**
     * 合并方块
     */
    private _mergeCount: number = 0;
    private _particleTimeout: number = -1;
    private async mergeGrid(curMatchGridArr: IBlock[], isCheckSingle: boolean = false) {
        if (curMatchGridArr.length == 0) {
            return Promise.resolve();
        }
        let self = this;
        let matchArr: IBlock[];
        //小的先消
        curMatchGridArr.sort((a, b) => {
            return a.type - b.type;
        })
        function search(tartget) {
            if (tartget.dirty) {
                matchArr = [];
                return;
            }
            for (let i = 0; i < tartget.neighbor.length; i++) {
                if (tartget.neighbor[i] == -1) {
                    continue;
                }
                let tempBlock: IBlock = self._blockManager.getBlockByIndex(tartget.neighbor[i]);
                if (tempBlock && tempBlock.type == tartget.type && matchArr.indexOf(tempBlock) == -1) {
                    if (tempBlock.type == BlockType.HT_2048 || tempBlock.dirty) {
                        matchArr = [];
                        break;
                    } else {
                        matchArr.push(tempBlock);
                        search(tempBlock);
                    }
                }
            }
        }

        return new Promise<any>((resolve, reject) => {
            let targetMatchGrid: IBlock = curMatchGridArr[0];
            matchArr = [targetMatchGrid];
            if (!targetMatchGrid || targetMatchGrid.type == 0) {
                if (targetMatchGrid) {
                    if (targetMatchGrid.type == 0) {
                        resolve();
                    }
                } else {
                    resolve();
                }
            } else {
                search(targetMatchGrid);
                if ((matchArr.length == 1 && isCheckSingle) || !matchArr.length) {
                    resolve();
                    return;
                }
                let targetType: number = targetMatchGrid.type + 1;
                if (matchArr.length > 2 || isCheckSingle) {
                    this._mergeCount++;
                    for (let i = 0; i < matchArr.length; i++) {
                        if (targetMatchGrid.index != matchArr[i].index) {
                            if (curMatchGridArr.indexOf(matchArr[i]) != -1) {
                                curMatchGridArr.splice(curMatchGridArr.indexOf(matchArr[i]), 1);
                            }
                            let node2: cc.Node = BlockManager.getInstance().getGridNodeByType(matchArr[i].type);
                            node2.scale = 0.7;
                            matchArr[i].type = BlockType.none;
                            matchArr[i].node.opacity = 255;
                            node2.parent = this.gridContainer;
                            node2.setPosition(matchArr[i].node.position);
                            let duration: number = 0.3;
                            this._manager.gameData.AddHexagon(matchArr[i].type, matchArr[i].index);
                            for (let j = 1; j <= 2; j++) {
                                let tempNode = cc.instantiate(node2);
                                tempNode.parent = this.gridContainer;
                                tempNode.setPosition(matchArr[i].node.position);
                                tempNode.scale = 0.7;
                                if (i == 2) {
                                    tempNode.opacity = 80;
                                } else {
                                    tempNode.opacity = 25;
                                }
                                tempNode.runAction(cc.sequence(cc.moveBy(duration / 2, tempNode.position.sub(targetMatchGrid.node.position).mul(0.5)), cc.delayTime(0.05 * j), cc.moveTo(duration - j * 0.05, targetMatchGrid.node.position), cc.callFunc(() => {
                                    tempNode.destroy();
                                })))
                            }
                            clearTimeout(this._particleTimeout);
                            let targetPos = targetMatchGrid.node.position;

                            node2.runAction(cc.sequence(
                                cc.moveBy(duration / 2, node2.position.sub(targetMatchGrid.node.position).mul(0.5)),
                                cc.moveTo(duration, targetPos),
                                cc.callFunc(() => {
                                    targetMatchGrid.type = targetType;
                                    //播放特效
                                    /* Utils.GetPrefab("prefab/Light", (prefab: cc.Prefab) => {
                                        let node: cc.Node = cc.instantiate(prefab);
                                        node.getComponent(cc.Sprite).spriteFrame = BlockManager.getInstance().gridSpriteFrameArr[targetMatchGrid.type];
                                        node2.parent.addChild(node);
                                        node.position = node2.position;
                                        node.runAction(cc.sequence(cc.spawn(cc.fadeOut(duration), cc.scaleTo(duration, 1.2, 1.2)), cc.callFunc(() => {
                                            node.destroy();
                                        })))
                                    }) */

                                    Utils.addAutoRemoveDragonBones(node2, "prefab/BombNode", "newAnimation", () => {
                                    }, this);
                                }),
                                cc.spawn(cc.scaleTo(duration, 1, 1), cc.fadeOut(duration)),
                                cc.callFunc(() => {
                                    GameManager.getInstance().audioManager.PlaySynthesiSound(this._mergeCount);
                                    node2.destroy();
                                    if (i == matchArr.length - 1) {
                                        let addScore: number = 0;
                                        if (this._mergeCount == 1) {
                                            addScore = blockTypeVals[targetMatchGrid.type - 1] * Math.pow(2, matchArr.length);
                                        } else {
                                            addScore = blockTypeVals[targetMatchGrid.type - 1] * Math.pow(2, matchArr.length + 1);
                                        }
                                        this._manager.gameData.AddCurScore(addScore);
                                        this._manager.eventCenter.DispatchEvent("block_score_update", { pos: targetMatchGrid.pos, score: addScore });

                                        this._manager.gameData.AddHexagon(targetMatchGrid.type, targetMatchGrid.index);

                                        this._blockManager.maxBlockLevel = targetMatchGrid.type;
                                        // Facebook.FBRank.SetScoreToGloalRank(100);//zgs_test
                                        if (addScore > 512) {
                                            this._particleTimeout = setTimeout(() => {
                                                Utils.GetPrefab("prefab/updateScoreParticlesystem.prefab", (prefab) => {
                                                    if (!prefab) return;
                                                    var particle = cc.instantiate(prefab);
                                                    if (particle) {
                                                        cc.find("Canvas").addChild(particle);
                                                        let worldPos = targetMatchGrid.node.parent.convertToWorldSpaceAR(targetPos);
                                                        particle.setPosition(particle.parent.convertToNodeSpaceAR(worldPos));
                                                        let scoreNodeWorldPos: cc.Vec2 = this.id.node.parent.convertToWorldSpaceAR(this.id.node.position);
                                                        let tempTargetPos: cc.Vec2 = particle.parent.convertToNodeSpaceAR(scoreNodeWorldPos);
                                                        let d = this.id.node.width;
                                                        tempTargetPos = tempTargetPos.add(cc.v2(this.id.node.width / 4, 0))
                                                        var bezier = [particle.position, particle.position.add(cc.v2(100, 100)), tempTargetPos];
                                                        particle.runAction(cc.sequence(cc.bezierTo(tempTargetPos.sub(scoreNodeWorldPos).normalize().mag() / 2, bezier), cc.delayTime(0.4), cc.callFunc(() => {
                                                            particle.destroy();
                                                        })));
                                                    }
                                                }, this);
                                            }, 1000);
                                        }
                                        setTimeout(() => {
                                            resolve();
                                        }, duration * 1000 + 100);
                                    }
                                }, this)))//.easing(cc.easeBackIn()));
                        }
                    }
                } else {
                    resolve();
                }
            }
        })
    }

    private restartHandler(): void {
        this._blockManager.reset();
        this.buildNextDragGrid();
        this._manager.gameData.ResetGameArchive();
        this._addPointPropState = 0;
        this._removeBlockPropState = 0;
    }

    private gameoverHandler(): void {
        this.restartHandler();
        GameManager.getInstance().sceneManager.switchScene(SceneManager.SceneType.GameScene, SceneManager.SceneSwitchType.UpToDown);
    }

    private goLobbyHandler(): void {
        // this.restartHandler();
        GameManager.getInstance().sceneManager.switchScene(SceneManager.SceneType.StartScene, SceneManager.SceneSwitchType.UpToDown);
    }

    /**
     * 读取存档
     */
    private readArchive(): void {
        let data = this._manager.gameData.onReadGameArchive();
        Logger.log(data);
        if (data) {
            for (const key in data.hexagon_data) {
                if (data.hexagon_data.hasOwnProperty(key)) {
                    const element = data.hexagon_data[key];
                    this._blockManager.blockArr[key].type = element;
                }
            }
            try {
                let dragData: IDragData = this._blockManager.dragData;
                dragData.posType = data.pos_type;
                dragData.blockArr = data.random_hexagon_data;
                if (dragData.blockArr.length) {
                    this.buildNextDragGrid(false, false);
                } else {
                    this.buildNextDragGrid();
                }
            } catch (err) {
                this.buildNextDragGrid();
            }

        } else {
            this.buildNextDragGrid();
        }
        this._manager.gameData.updateUIArchive();
        
        if (BlockManager.getInstance().checkGameOver()) {
            this.openReadArchive();
        }
    }

    /**
     * 刷新方块(改成分数+1)
     */
    private _addPointPropState: number = 0;
    private refreshHandler(time: number = 0): void {
        this.showPropPromptPanel(PROP_TYPE.FINGER);
        this._addPointPropState = 1;
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartHandler, this);
        // let olddragData: IDragData = this._blockManager.dragData;
        // let newdragData: IDragData;
        // this.buildNextDragGrid();
        // newdragData = this._blockManager.dragData;
        // if (newdragData.blockArr.indexOf(olddragData.blockArr[0]) != -1 && newdragData.blockArr.indexOf(olddragData.blockArr[1]) != -1
        //     && time < 5) {
        //     this.refreshHandler(time++);
        // }
    }

    private _removeBlockPropState: number = 0;
    private removeBlockHandler(): void {
        this.showPropPromptPanel(PROP_TYPE.HAMMER);
        this._removeBlockPropState = 1;
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartHandler, this);
    }
    /**显示道具提示界面 */
    private showPropPromptPanel(type: PROP_TYPE) {
        Utils.GetPrefab("prefab/propPromptPanel.prefab", (prefab) => {
            if (prefab && (!this._propPromptPanel || !this._propPromptPanel.parent)) {
                this._propPromptPanel = cc.instantiate(prefab);
                this.node.addChild(this._propPromptPanel);
                let prop = this._propPromptPanel.getComponent("PropPromptPanel");
                prop.initData(type);
            }
        }, this)
    }
    /**移除道具提示界面 */
    private removePropPromptPanel() {
        this._addPointPropState = this._removeBlockPropState = 0;
        this.node.removeChild(this._propPromptPanel)
        this._propPromptPanel && this._propPromptPanel.getComponent("PropPromptPanel").destroy();
        this._propPromptPanel = null;
    }


    private playEncourage(mergeCount): void {
        let audioManager: AudioManager = GameManager.getInstance().audioManager;
        if (mergeCount == 2) {
            let node: cc.Node = new cc.Node();
            node.parent = cc.find("Canvas");
            node.y = 400;
            audioManager.playEffect("good");
            Utils.AddAutoRemoveEffect(node, "prefab/goodAnim", "goodAnim", () => {
                node.destroy();
            }, this);
        } else if (mergeCount == 3) {
            audioManager.playEffect("nice");
            let node: cc.Node = new cc.Node();
            node.parent = cc.find("Canvas");
            node.y = 400;
            Utils.AddAutoRemoveEffect(node, "prefab/niceAnim", "niceAnim", () => {
                node.destroy();
            }, this);
        } else if (mergeCount >= 4) {
            audioManager.playEffect("perfect");
            let node: cc.Node = new cc.Node();
            node.parent = cc.find("Canvas");
            node.y = 400;
            Utils.AddAutoRemoveEffect(node, "prefab/perfectAnim", "perfectAnim", () => {
                node.destroy();
            }, this);
        }
    }
}
